import { defineStore } from 'pinia';
import curdUtils from "/@/stores/ums/customer/curdUtils";
import {umsMemberStateApi as api} from "/@/api/ums/member/stateApi";
import {ElMessage} from "element-plus";


/**
 * 客户经营范围
 */
export const businessScopeCache = defineStore('businessScope', {
	state: ():any => ({
		// 客户经营范围 - 列表
		list: [],
		// 客户经营范围  - get 加载的锁
		lock: false,
		// 类型
		type: 1,
		// 标题
		title: '客户经营范围'
	}),
	actions: {

		/** 查找指定业务范围信息 */
		findById(id: string): string {
			const i = this.list.findIndex((fi:any) => id === fi.id)
			if (i === -1)
				return ""
			return this.list[i].name
		},

		/**
		 * 添加
		 * @param domain 添加数据对象
		 */
		async add(domain:any): Promise<boolean>{
			if (!domain){
				return false
			}
			// 添加类型
			domain['type'] = this.type;
			// 保存到数据库
			return await this.addData(domain, api, this.loadList, this.title)
		},

		/**
		 * 获取
		 * 1、不一定立即能获取到
		 * 2、因为有异步加载，返回的对象是引用
		 */
		getList(): Array<any> {
			// 检查是否有数据
			if (this.isLoad(this.lock, this.list)) {
				this.lock = true
				this.loadList()
			}
			return this.list
		},

		/** 加载 */
		async loadList(){
			try{
				const params = {'type': this.type};
				const {data} = await api().query(params);
				// 清除重新加载
				this.checkReset(this.list)
				// 增量加载 - 直接赋值会导致引用失效
				this.list.push(...data);
			}catch (e:any){
				console.log('获取'+this.title+'列表异常捕获\n',e);
				ElMessage.error(e.message)
			}
			this.lock = false
		},

		/**
		 * 批量修改显示或隐藏
		 * @param ids 需要显示 ID 空则全部不显示
		 */
		async batchVisibleByIds(ids:any): Promise<boolean>{
			return await this.doBatchVisible(ids, {'type': this.type}, api, this.loadList, this.title)
		},

		 init(){
			if (this.isLoad(this.lock, this.list)) {
				this.lock = true
				this.loadList()
			}
		},

		// 公共方法
		...curdUtils
	},

	persist: {
		// 开启持久化
		enabled: true,
		strategies: [
			{
				key: '17-work-businessScopeCache',
				storage: sessionStorage, // 仅会话期间有效
				paths: ['list']
			},
			// {storage: localStorage, paths: ['']},
		],
	},

});



